import { createStore } from "vuex";
import createPersistedState from 'vuex-persistedstate'
const store = createStore({
    state:{
        username:"",
        password:"",
        carts:[]
    },
    getters:{
        isLogin(state){
            return state.username!=''&&state.password!=''
        },
        getNum(state){
            if(state.carts.length===0){
                return 0
            }else{
                var num = 0
                for(var item of state.carts){
                    num = num + item.num
                }
                return num
            }
        },
        getAllFlag(state){
            if(state.carts.length===0){
                return 0
            }else if(state.carts.every(target=>target.flag===1)){
                return 1
            }else{
                return 0
            }
        },
        getFlagCart(state){
            return state.carts.filter(cart=>cart.flag===1)
        }
    },
    mutations:{
        login(state,payload){
            state.username = payload.username
            state.password = payload.password
        },
        outLogin(state){
            state.username = "",
            state.password = ""
        },
        add(state,payload){
            var cart = state.carts.find((item)=>item.id===payload)
            if(cart){
                state.carts.forEach((item,index)=>{
                    if(item.id === payload){
                        state.carts[index].num = state.carts[index].num + 1
                    }
                })
            }else{
                state.carts.push({id:payload,num:1,flag:0})
            }
        },
        reduce(state,payload){
            state.carts.forEach((item,index)=>{
                if(item.id===payload){
                    state.carts[index].num = state.carts[index].num - 1
                }
            })
        },
        delete(state,payload){
            state.carts.forEach((item,index)=>{
                if(item.id===payload){
                    state.carts.splice(index,1)
                }
            })
        },
        upFlag(state,payload){
            state.carts.forEach((item,index)=>{
                if(item.id===payload){
                    state.carts[index].flag = state.carts[index].flag === 1?0:1
                }
            })
        },
        upAllFlag(state,payload){
            state.carts.forEach((item,index)=>{
                state.carts[index].flag = payload
            })
        },
        
    },
    plugins:[createPersistedState({
            storage:window.localStorage
        })]
})
export default store